package com.bf.hotpoint.repository.mongo;

import static org.springframework.data.mongodb.core.query.Criteria.where;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;

import com.bf.hotpoint.domain.Message;
import com.bf.hotpoint.domain.Reply;
import com.bf.hotpoint.domain.Subject;
import com.mongodb.WriteResult;

import static org.springframework.data.mongodb.core.query.Query.query;
import static org.springframework.data.mongodb.core.query.Update.update;

/*
 * 废弃
 * */
@Repository
public class SubjectMongoRepository
{
	@Autowired
	private MongoTemplate mongoTemplate;
	
	public void addSubject(String subjectContent)
	{
		if(subjectContent != null){
			Subject subject = mongoTemplate.findOne(query(where("subjectContent").is(subjectContent)), Subject.class);
			if(subject != null)
			{
				subject.setUsedTimes((subject.getUsedTimes()+1));
				this.updateSubject(subject);
			}
			else
			{
				Subject newSubject = new Subject();
				newSubject.setSubjectContent(subjectContent);
				newSubject.setTop(false);
				newSubject.setUsedTimes(1);
				mongoTemplate.save(newSubject);
			}
		}
	}
	
	public void deleteSubject(String subjectContent)
	{
		Subject subject = mongoTemplate.findOne(query(where("subjectContent").is(subjectContent)), Subject.class);
		
		if(subject != null)
		{
			subject.setUsedTimes((subject.getUsedTimes()-1));
			this.updateSubject(subject);
		}
		if(subject != null && subject.getUsedTimes() < 1)
		{
			WriteResult writeResult = mongoTemplate.remove(query(where("subjectContent").is(subjectContent)), Subject.class);
			boolean isSuccess = writeResult.getN() <= 0 ? false : true;
		}
	}
	
	public boolean updateSubject(Subject subject)
	{
		WriteResult writeResult = null;
		if(subject != null){
			if(mongoTemplate.findById(subject.getSubjectId(), Subject.class) != null)
			{
				writeResult = mongoTemplate.updateFirst(query(where("subjectId").is(subject.getSubjectId())), update(subject.getSubjectId(),subject), Subject.class);
			}
		}
		if(writeResult == null){
			return false;
		}
		return writeResult.getN() <= 0 ? false : true;
	}
	
	public Subject getSubjectBySubjectContent(String subjectContent)
	{
		return mongoTemplate.findOne(query(where("subjectContent").is(subjectContent)), Subject.class);
	}
}